package com.linshengjian.snowball.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;

@Configuration
public class SpringContextUtils implements ApplicationContextAware {
    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static ApplicationContext getContext() {

        return context;
    }

    public static <T> T getInstance(Class<T> clazz) throws IllegalAccessException, InstantiationException {
        try{
            return SpringContextUtils.getContext().getBean(clazz);
        } catch (NoSuchBeanDefinitionException e) {
            return clazz.newInstance();
        }
    }
}